<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>01-05 reduce</title>
</head>

<body>
  <h1>数组之和</h1>

  <script>
    // 111 循环 5次
    function sum(array) {
      let res = 0
      for (let i = 0; i < array.length; i++) {
        res += array[i]
        // console.log('111 循环 i', i)
      }
      return res
    }

    const arr = [1, 2, 3, 4, 5]
    console.log('111 sum=', sum(arr))

    // 222 循环 4次
    const sum2 = arr.reduce((pre, cur) => {
      // console.log('222 循环')
      return pre * 1 + cur * 1
    })
    console.log('222 sum=', sum2)

    // 333 循环 3次
    function sum3(array) {
      if (!array) return 0
      const len = array.length
      if (len === 1) return array[0]
      const max = Math.ceil(len / 2)
      let res = 0
      for (let i = 0; i < max; i++) {
        const lastIndex = len - i - 1
        let lastNum = 0
        if (i !== lastIndex) {
          lastNum = array[lastIndex]
        }
        res += array[i] + lastNum
      }
      console.log('333 sum3 循环次数:', max)
      return res
    }

    console.log('333 sum=', sum3(arr))
  </script>
</body>

</html>